﻿using Castle.DynamicProxy;
using AspNetCore.HttpClientAndPolly.PollyAttribute;
using Polly;
using System;
using System.Linq;
using System.Reflection;

namespace AspNetCore.HttpClientAndPolly.PollyHelper
{
    /// <summary>
    /// 拦截器
    /// </summary>
    public class CustomInterceptor : StandardInterceptor
    {
        protected override void PreProceed(IInvocation invocation)
        {
            base.PreProceed(invocation);
        }

        protected override void PerformProceed(IInvocation invocation)
        {
            ISyncPolicy policy = null;
            Action<ISyncPolicy> action = policy => policy.Execute(() => base.PerformProceed(invocation));
            if (invocation.Method.IsDefined(typeof(PollyRetryAttribute), true))
            {
                var attributeList = invocation.Method.GetCustomAttributes<PollyRetryAttribute>().Reverse().OrderByDescending(t => t.Order);
                foreach (var attribute in attributeList)
                {
                    action = attribute.Do(action);
                }
            }
            action(policy); 
        }

        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="invocation"></param>
        protected override void PostProceed(IInvocation invocation)
        {
            base.PostProceed(invocation);
        }
    }
}
